package com.denlaku.longan.service.impl;

import com.denlaku.longan.event.MessageEventProducer;
import com.denlaku.longan.qo.ObjPermQuery;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.repository.ObjectTagRepository;
import com.denlaku.longan.service.ObjectTagRelService;
import com.denlaku.longan.service.ObjectTagService;
import com.denlaku.longan.vo.ObjectTag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tianx
 */
@Slf4j
@Service
public class ObjectTagServiceImpl implements ObjectTagService {
    @Autowired
    private ObjectTagRepository objectTagRepository;

    @Autowired
    private ObjectTagRelService objPermRelService;

    @Autowired
    private MessageEventProducer messageEventProducer;

    @Override
    public void add(ObjectTag objectTag) {
        objectTagRepository.add(objectTag);
    }

    @Override
    public void update(ObjectTag objectTag) {
        objectTagRepository.update(objectTag);
    }

    @Override
    public ObjectTag get(Query query) {
        return objectTagRepository.get(query);
    }

    @Override
    public List<ObjectTag> list(Query query) {
        return objectTagRepository.list(query);
    }

    @Override
    public Map<Long, String> getTagNameMap(Query query) {
        List<ObjectTag> objectTags = objectTagRepository.listByIds(query);
        Map<Long, String> tagMap = objectTags.stream()
            .collect(Collectors.toMap(ObjectTag::getId, ObjectTag::getName, (v1, v2) -> v2));
        return tagMap;
    }

    @Override
    public List<ObjectTag> search(Query query) {
        return objectTagRepository.search(query);
    }

    @Override
    public void delete(ObjPermQuery query) {
        ObjectTag objectTag = this.get(query);
        if (objectTag == null) {
            return;
        }
        objectTagRepository.delete(query);

        ObjPermQuery relQuery = new ObjPermQuery();
        relQuery.setTagSetId(query.getId());
        objPermRelService.delete(relQuery);

        messageEventProducer.onData(objectTag);
    }
}
